package com.ai.enviro.module.system.service;

import com.ai.enviro.module.system.dao.IotEnvStorage;
import com.ai.enviro.module.system.dao.dataobject.IotEnvDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class IotEnvService {
    @Autowired
    @Qualifier("iotEnvDbStorage")
    private IotEnvStorage iotEnvStorage;
    public void saveIotEnv(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b & 0xff));
        }
        log.info(sb.toString());
        if (bytes.length < 8) {
            log.info("Invalid data length");
            return;
        }

        // 提取红色框内的字节
        byte[]  humidityBytes = new byte[] {bytes[3], bytes[4]};
        byte[] temperatureBytes = new byte[] {bytes[5], bytes[6]};

        // 计算温度和湿度
        int temperature = calculateValue(temperatureBytes);
        int humidity = calculateValue(humidityBytes);

        log.info("Temperature: " + temperature / 10.0);
        log.info("Humidity: " + humidity / 10.0);
        iotEnvStorage.save(temperature, humidity);
    }
    private int calculateValue(byte[] byteArray) {
        // 转换为16进制字符串
        String hexString = String.format("%02x%02x", byteArray[0], byteArray[1]);
        int value = Integer.parseInt(hexString, 16);

        // 检查是否为负数并转换
        return value > 32767 ? value - 65536 : value;
    }

    public IotEnvDO getIotEnv() {
        return iotEnvStorage.getIotEnv();
    }


    public static double calculateValue2(int value) {
        // 将整数转换为二进制字符串，并确保该字符串长度为16位，不足的前面补零
        String binaryString = String.format("%16s", Integer.toBinaryString(value)).replace(' ', '0');

        // 判断最高位，如果是0，表示正数；如果是1，表示负数
        if (binaryString.charAt(0) == '0') {
            return value;
        } else {
            return (value - 65536) ;
        }
    }


}
